<!--
 * @Author: Pure <305737824@qq.com>
 * @CreateTime: 2021-04-17 00:01:59
 * @LastEditors: Pure <305737824@qq.com>
 * @LastEditTime: 2022-03-18 13:55:38
 * @Description:上传组件
-->
<template>
  <div>
    <el-upload
      ref="upload"
      :file-list="fileList"
      action="api/busLocalFile/upload"
      :class="{hide:disabled}"
      multiple
      :headers="headers"
      :on-success="handleSuccess"
      :on-preview="handlePreview"
      :on-remove="removeFile"
      :auto-upload="true"
      :list-type="listType"
      :before-upload="beforeUploadFile"
    >
      <el-button v-if="listType==='text'" size="small" type="primary">点击上传</el-button>
      <i v-else-if="listType==='picture-card'" class="el-icon-plus" />
      <div v-if="listType==='picture-card'" slot="file" slot-scope="{file}">
        <img
          class="el-upload-list__item-thumbnail"
          :src="fileBaseUri+file.url"
          alt=""
        >
        <span class="el-upload-list__item-actions">
          <span
            class="el-upload-list__item-preview"
            @click="handlePreview(file)"
          >
            <i class="el-icon-zoom-in" />
          </span>
          <span
            v-if="!disabled"
            class="el-upload-list__item-delete"
            @click="removeFile(file)"
          >
            <i class="el-icon-delete" />
          </span>
        </span>
      </div>
    </el-upload>
    <preview v-if="showPreview" :z-index="9999" :initial-index="currentIndex" :on-close="closePreview" :url-list="previewFileList " />
  </div>
</template>

<script>
export default {
  name: 'Upload',
  components: {
    // 直接引用element-ui 中的预览组件
    preview: () => import('element-ui/packages/image/src/image-viewer'),
  },
  props: {
    value: {
      type: String,
      default: JSON.stringify([]),
    },
    listType: {
      type: String,
      default: 'text',
    },
    disabled: {
      type: Boolean,
      default: false,
    },

  },
  data() {
    return {
      showPreview: false,
      currentPreviewImg: null,
      currentIndex: 0,
      currentFiles: null,
      fileBaseUri: this.$store.state.login.uriConfig.fileBaseUri,
    };
  },
  computed: {
    headers() {
      return { token: this.$store.state.login.accessToken, };
    },
    fileList: {
      set(val) {
        this.$emit('change', JSON.stringify(val));
        this.$emit('input', JSON.stringify(val));
      },
      get() {
        const value = this.value ? JSON.parse(this.value) : [];
        return value;
        // return value instanceof Array && value.length ? value : JSON.parse(this.list);
      },
    },
    previewFileList() {
      const reg = /\.(png|jpg|gif|jpeg|webp)$/;
      const rightFile = this.fileList.filter(e => reg.test(e.name));
      const f = rightFile.map(e => this.$store.state.login.uriConfig.fileBaseUri + e.url);
      return f;
    },
  },
  mounted() {
    // this.$refs.upload.upload
  },
  methods: {
    /**
     * 文件上传之前的处理
     */
    beforeUploadFile(f) {
      this.currentFiles = f;
    },
    handleSuccess(res) {
      if (res.code === 0) {
        this.fileList = [...this.fileList, ...[{
          name: res.body.oldName,
          url: `${res.body.path}/${res.body.fileName}`,
        }]];
      } else {
        this.$message({
          type: 'error',
          message: '文件上传失败',
        });
        const uid = this.currentFiles.uid; // 关键作用代码，去除文件列表失败文件
        const idx = this.$refs.upload.uploadFiles.findIndex(item => item.uid === uid); // 关键作用代码，去除文件列表失败文件（uploadFiles为el-upload中的ref值）

        this.$refs.upload.uploadFiles.splice(idx, 1); // 关键作用代码，去除文件列表失败文件
      }
    },
    closePreview() {
      this.showPreview = false;
    },
    handlePreview(file) {
      const reg = /(.jpg|.png|.jpeg|.svg|.gif)/g;
      if (!reg.test(file.name)) {
        const url = `${this.$store.state.login.uriConfig.fileBaseUri}${file.url}`;
        window.location.href = url;
        return;
        // return this.$message.error('该格式暂不支持预览！');
      }
      this.fileList.forEach((e, i) => {
        if (file.name === e.name) {
          this.currentPreviewImg = this.$store.state.login.uriConfig.fileBaseUri + e.url;
          this.currentIndex = this.previewFileList.indexOf(this.currentPreviewImg);
          this.showPreview = true;
        }
      });
    },
    removeFile(file, list) {
      const fileList = this.$refs.upload.uploadFiles;
      const index = fileList.findIndex(fileItem => {
        return fileItem.uid === file.uid;
      });
      fileList.splice(index, 1);
      this.fileList = fileList;
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .hide {
  .el-upload--picture-card,.el-upload--text {
    display: none;
  }
}
.el-upload-list__item-thumbnail {
  position:absolute;
  object-fit: cover;
}
</style>
